package com.example.multithreading;

import org.springframework.util.StopWatch;

import java.util.concurrent.*;

public class SynchronizedPoolTest {

    public static void main(String[] args) {
        SynchronizedPoolTest synchronizedPoolTest = new SynchronizedPoolTest();
        synchronizedPoolTest.poolTest();
        synchronizedPoolTest.forTest();
    }

    /**
     * 方法说明：使用线程池
     * @param
     * @return void
     * @throws
     * @Author xiaohf
     * @Date 2021/9/22 20:09
     **/
    public void poolTest(){

        ThreadDemo threadDemo = new ThreadDemo();
//        ExecutorService executorService = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor singleThreadPool = new ThreadPoolExecutor(500, 1000,
                10000L, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(1024),  new ThreadPoolExecutor.AbortPolicy());
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        for (int i = 0; i < 100; i++) {

            Future<?> future = singleThreadPool.submit(() -> {
                threadDemo.getCount();
//                System.out.println("线程池中线程数目：" + singleThreadPool.getPoolSize()+":"+singleThreadPool.getActiveCount() + "，队列中等待执行的任务数目：" +
//                        singleThreadPool.getQueue().size() + "，已执行完的任务数目：" + singleThreadPool.getCompletedTaskCount());
            });
        }
        singleThreadPool.shutdown();
        do {
            if(singleThreadPool.getActiveCount() == 0 && stopWatch.isRunning()){
                stopWatch.stop();
                System.out.println(stopWatch.getLastTaskTimeMillis());
                break;
            }
        } while (true);
    }

    /**
     * 方法说明：普通for循环
     * @param
     * @return void
     * @throws
     * @Author xiaohf
     * @Date 2021/9/22 20:10
     **/
    public void forTest() {

        ThreadDemo threadDemo = new ThreadDemo();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        for (int i = 0; i < 100; i++) {
            threadDemo.getCount();
        }
        stopWatch.stop();
        System.out.println(stopWatch.getLastTaskTimeMillis());
    }
}


